package com.tuniondata.netty.client;

import com.tuniondata.netty.bean.ApiBinaryBean;
import com.tuniondata.netty.bean.RpcMessage;
import com.tuniondata.netty.client.future.SyncRequestFuture;
import com.tuniondata.netty.client.future.SyncRequestMap;
import com.tuniondata.netty.common.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApiClientHandler extends SimpleChannelInboundHandler {
    private static Logger logger = LoggerFactory.getLogger(ApiClientHandler.class);

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            logger.info("客户端收到服务器响应信息.");
            RpcMessage rpcMessage = (RpcMessage) msg;
            Protocol protocol = rpcMessage.getProtocol();
            ApiClientProcessor processor = new ApiClientProcessor();
            String mtp = protocol.getMessageType();
            logger.info("client mtp:{}", mtp);
            RpcMessage response = null;
            response = processor.process(rpcMessage);
            if (response == null) {
                logger.debug("mtp:{} not supported", mtp);
                protocol.setBody("");
            }
            // 设置响应
            String requestId = rpcMessage.getRequestId();
            SyncRequestFuture future = (SyncRequestFuture) SyncRequestMap.syncKey.get(requestId);
            if (future != null) {
                logger.info("setting response, {}", rpcMessage);;
                future.setResponse(rpcMessage);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            exceptionCaught(ctx, e.getCause());
        }
    }
}
